package top.mcwebsite.playandroid.common.anim

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.abs

val colorList = listOf(
    Color(0xFFFF0000),
    Color(0xFFFF7D00),
    Color(0xFFFFFF00),
    Color(0xFF00FF00),
    Color(0xFF00FFFF),
    Color(0xFF0000FF),
    Color(0xFFFF00FF),
)

@Composable
fun JumpBall(
    modifier: Modifier = Modifier,
    colors: List<Color> = colorList,
    radius: Dp = 5.dp
) {
    val transition = rememberInfiniteTransition(label = "JumpBall")
    val minHeight = with(LocalDensity.current) {
        70f.toDp() + radius
    }

    val minWidth = radius * 2 * 14
    val anim = transition.animateFloat(
        initialValue = 0f, targetValue = 70f, animationSpec = InfiniteRepeatableSpec(
            tween(durationMillis = 1000, easing = FastOutSlowInEasing), repeatMode = RepeatMode.Reverse
        ), label = ""
    )


    Canvas(
        modifier = modifier
            .width(minWidth)
            .height(minHeight)
    ) {
        colors.forEachIndexed { index, color ->
            val offsetY = anim.value - index * 10
            drawCircle(
                color,
                radius = radius.toPx(),
                center = Offset(size.width / 7 * (index + 1),  radius.toPx() / 2 + abs(offsetY))
            )
            size.width / 7
        }
    }
}

@Preview
@Composable
fun JumpBallPreview() {
    Box(modifier = Modifier.fillMaxWidth()) {
        JumpBall(
            modifier = Modifier
                .align(Alignment.Center)
        )
    }
}